// 全局变量
let cartItems = [];

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    checkLoginStatus();
    loadCartItems();
});

// 检查登录状态
function checkLoginStatus() {
    const token = localStorage.getItem('token');
    if (!token) {
        alert('请先登录');
        window.location.href = '/login.html';
        return;
    }
}

// 加载购物车商品
async function loadCartItems() {
    try {
        const response = await fetch('/api/cart', {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });
        
        if (!response.ok) {
            throw new Error('加载购物车失败');
        }
        
        cartItems = await response.json();
        displayCartItems();
        updateTotalPrice();
    } catch (error) {
        console.error('加载购物车失败:', error);
        alert('加载购物车失败');
    }
}

// 显示购物车商品
function displayCartItems() {
    const cartList = document.getElementById('cartList');
    cartList.innerHTML = '';

    if (cartItems.length === 0) {
        cartList.innerHTML = '<div class="alert alert-info">购物车为空</div>';
        return;
    }

    cartItems.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>
                <img src="${item.product.image_url || 'images/default-product.jpg'}" 
                     class="cart-item-image" alt="${item.product.name}">
            </td>
            <td>${item.product.name}</td>
            <td>¥${item.product.price}</td>
            <td>
                <div class="input-group">
                    <button class="btn btn-outline-secondary" 
                            onclick="updateQuantity(${item.id}, ${item.quantity - 1})">-</button>
                    <input type="number" class="form-control text-center" 
                           value="${item.quantity}" min="1" 
                           onchange="updateQuantity(${item.id}, this.value)">
                    <button class="btn btn-outline-secondary" 
                            onclick="updateQuantity(${item.id}, ${item.quantity + 1})">+</button>
                </div>
            </td>
            <td>¥${(item.product.price * item.quantity).toFixed(2)}</td>
            <td>
                <button class="btn btn-danger" onclick="removeFromCart(${item.id})">
                    删除
                </button>
            </td>
        `;
        cartList.appendChild(row);
    });
}

// 更新商品数量
async function updateQuantity(cartItemId, newQuantity) {
    if (newQuantity < 1) {
        newQuantity = 1;
    }

    try {
        const response = await fetch(`/api/cart/${cartItemId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify({ quantity: newQuantity })
        });

        if (!response.ok) {
            throw new Error('更新数量失败');
        }

        loadCartItems();
    } catch (error) {
        console.error('更新数量失败:', error);
        alert('更新数量失败');
    }
}

// 从购物车删除商品
async function removeFromCart(cartItemId) {
    try {
        const response = await fetch(`/api/cart/${cartItemId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        if (!response.ok) {
            throw new Error('删除失败');
        }

        loadCartItems();
    } catch (error) {
        console.error('删除失败:', error);
        alert('删除失败');
    }
}

// 更新总价
function updateTotalPrice() {
    const totalPrice = cartItems.reduce((sum, item) => {
        return sum + (item.product.price * item.quantity);
    }, 0);

    document.getElementById('totalPrice').textContent = `¥${totalPrice.toFixed(2)}`;
}

// 结算
async function checkout() {
    if (cartItems.length === 0) {
        alert('购物车为空');
        return;
    }

    try {
        const response = await fetch('/api/orders', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify({
                items: cartItems.map(item => ({
                    productId: item.product.id,
                    quantity: item.quantity
                }))
            })
        });

        if (!response.ok) {
            throw new Error('创建订单失败');
        }

        const order = await response.json();
        alert('订单创建成功');
        window.location.href = `/order.html?id=${order.id}`;
    } catch (error) {
        console.error('创建订单失败:', error);
        alert('创建订单失败');
    }
} 